import { Base } from '../../utils/base.js';


class Cart extends Base{
  
  constructor() {
    super();
    this._storageKeyName = 'cart';
  }

  // 添加商品至购物车
  add(item,counts){
    var cartData = this.getCartDataFromLocal();
    var isHasInfo = this._isHasThatOne(item.id,cartData);
    if (isHasInfo.index == -1){
      item.counts = counts;
      item.selectStatus = true;
      cartData.push(item);
    }else{
      cartData[isHasInfo.index].counts += counts;
    }
    wx.setStorageSync(this._storageKeyName, cartData);
  }

  // 获取购物车本地缓存数据
  getCartDataFromLocal(flag=false) {
    var res = wx.getStorageSync(this._storageKeyName);
    var newRes = [];
    if(!res){
      res = [];
    }
    if(flag){
      for(let i=0;i<res.length;i++){
        if (res[i].selectStatus){
          newRes.push(res[i]);
        }
      }
      res = newRes;
    }
    return res;
  }

  // 判断当前商品是否存在于购物车
  _isHasThatOne(id,arr) {
    var item,
    result = { index:-1 };
    for(let i=0;i<arr.length;i++){
      item = arr[i];
      if(item.id == id){
        result = {
          index : i,
          data : item,
        };
        break;
      }
    }
    return result;
  }

  // 计算购物车数量
  getCartTotalCounts(flag=false) {
    var data = this.getCartDataFromLocal(flag);
    console.log(data);
    var counts = 0;
    for(let i=0;i<data.length;i++){
      counts += data[i].counts;
    }
    return counts;
  }

  // 更改商品数量
  _changeCounts(id,counts){
    var cartData = this.getCartDataFromLocal(),
    hasInfo = this._isHasThatOne(id,cartData);
    if(hasInfo.index != -1){
      if (hasInfo.data.counts > 1){
        cartData[hasInfo.index].counts += counts;
      }
    }
    wx.setStorageSync(this._storageKeyName, cartData);
  }

  // 增加商品数量
  addCounts(id){
    this._changeCounts(id,1);
  }

  // 减少商品数量
  cutCounts(id) {
    this._changeCounts(id, -1);
  }

  // 删除购物车商品
  _deleteCartData(ids){
    
    if(!(ids instanceof Array)){
      ids=[ids];
    }
    var cartData = this.getCartDataFromLocal();
    for (let i = 0; i < ids.length;i++){
      var hasInfo = this._isHasThatOne(ids[i],cartData);
      if (hasInfo.index != -1){
        cartData.splice(hasInfo.index, 1);
      }
    }
    wx.setStorageSync(this._storageKeyName, cartData);
  }

}

export { Cart };